package com.oros.db;

import java.io.Serializable;

import com.vaadin.data.Item;
import com.vaadin.data.Container.Filter;

public class AEEqualFieldFilter implements Filter, Serializable {

	private static final long serialVersionUID = 8951940498598334725L;
	private String column1,column2;
	private int operation;
	public final static int OPERATION_EQUAL=0;
	public final static int OPERATION_NOTEQUAL=1;
	public final static int OPERATION_GREATER=2;
	public final static int OPERATION_LESS=3;
	public final static int OPERATION_GREATEROREQUAL=4;
	public final static int OPERATION_LESSOREQUAL=5;
    public AEEqualFieldFilter(String column1,String column2,int operation)
    {
    	this.column1 = column1;
    	this.column2 = column2;
    	this.operation = operation;
    }
	@SuppressWarnings("unchecked")
	@Override
	public boolean passesFilter(Object itemId, Item item)
			throws UnsupportedOperationException {
		Object dat1=item.getItemProperty(column1).getValue();
		Object dat2=item.getItemProperty(column2).getValue();
		if (dat1==null && dat2==null)
		{
			if (operation==OPERATION_EQUAL) return  true;
            return false;
		}
		if (dat1==null || dat2==null)
		{
			if (operation==OPERATION_NOTEQUAL) return true;
			return false;
		}
		Comparable<Object> cdat1=null;
		if (dat1 instanceof Comparable) cdat1=(Comparable<Object>)dat1;
		else if (operation>=OPERATION_GREATER) return false;
		switch(operation)
		{
		case OPERATION_EQUAL:
			 return dat1.equals(dat2);
		case OPERATION_NOTEQUAL:
			 return !dat1.equals(dat2);
		case OPERATION_GREATER:
			 return cdat1.compareTo(dat2)>0;
		case OPERATION_LESS:
			 return cdat1.compareTo(dat2)<0;
		case OPERATION_GREATEROREQUAL:
			 return cdat1.compareTo(dat2)>=0;
		case OPERATION_LESSOREQUAL:
			 return cdat1.compareTo(dat2)<=0;
		}
		return false;
	}

	@Override
	public boolean appliesToProperty(Object propertyId) {
		return column1.equals(propertyId) || column2.equals(propertyId);
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((column1 == null) ? 0 : column1.hashCode());
		result = prime * result + ((column2 == null) ? 0 : column2.hashCode());
		result = prime * result + operation;
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AEEqualFieldFilter other = (AEEqualFieldFilter) obj;
		if (column1 == null) {
			if (other.column1 != null)
				return false;
		} else if (!column1.equals(other.column1))
			return false;
		if (column2 == null) {
			if (other.column2 != null)
				return false;
		} else if (!column2.equals(other.column2))
			return false;
		if (operation != other.operation)
			return false;
		return true;
	}

}
